﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CDV.IRMS.WebAPI.TaskExecution.Interface.Impl
{
    /// <summary>
    /// 缓存服务实现类
    /// </summary>
    public class CacheServiceImp : ICacheService
    {
        /// <summary>
        /// 锁定节点的缓存
        /// </summary>
        private readonly ConcurrentDictionary<string, string> _lockedNodes = new ConcurrentDictionary<string, string>();

        /// <summary>
        /// 锁定节点的缓存
        /// </summary>
        public ConcurrentDictionary<string, string> LockedNodes
        {
            get
            {
                return _lockedNodes;
            }
        }

        /// <summary>
        /// 缓存锁定路由节点
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="routeID">路由ID</param>
        /// <param name="routeNodeID">路由节点ID</param>
        public void AddLockedNode(int taskID, int routeID, string routeNodeID)
        {
            _lockedNodes.AddOrUpdate($"{taskID}_{routeID}", routeNodeID, (key, value) => { return value; });
        }

        /// <summary>
        /// 移除锁定路由节点的缓存
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="routeID">路由ID</param>
        /// <returns>-1:移除失败；否则为路由节点ID</returns>
        public string RemoveLockedNode(int taskID, int routeID)
        {
            return _lockedNodes.TryRemove($"{taskID}_{routeID}", out string routeNodeId) ? routeNodeId : string.Empty;
        }
    }
}
